<?php
// +----------------------------------------------------------------------
// | ThinkCMF [ WE CAN DO IT MORE SIMPLE ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2018 http://www.thinkcmf.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 小夏 < 449134904@qq.com>
// +----------------------------------------------------------------------
namespace app\admin\controller;

use cmf\controller\AdminBaseController;
use think\Db;


class RegisterController extends AdminBaseController
{
    //列表
    public function index(){ //群众

      $this->comIndex();
        return $this->fetch('index');
    }
    public function index1(){ //社员
        $this->comIndex();
        return $this->fetch('index');
    }
    public function index2(){
        $this->comIndex();
        return $this->fetch('index');
    }
    public function index3(){
        $this->comIndex();
        return $this->fetch('index');
    }
    public function index4(){
        $this->comIndex();
        return $this->fetch('index');
    }
    private function comIndex(){
        $keyword = request()->param('keyword');
        $lev = request()->param('lev');
        $company_id = request()->param('company_id');

        if(!empty($keyword)){
            $where['phone|name']=['like','%'.$keyword.'%'];
        }
        if (!empty($company_id)){
            $where['company_id'] = $company_id;
        }
        $admin_id = cmf_get_current_admin_id();
        if ($admin_id != 1){
            $company_id = db('company')->where('user_id', $admin_id)->value('id');
            $where['company_id'] = $company_id;
        }
        if(!empty($lev)){
            switch ($lev){
                case 1:  $where['lev']=['eq',1];
                    break;
                case 2:  $where['lev']=['eq',2];
                    break;
                case 3:  $where['lev']=['eq',3];
                    break;
                case 4:  $where['lev']=['eq',4];
                    break;
                case 5:  $where['lev']=['eq',5];
                    break;
            }

        }
        $where['is_del'] = 0;
        // dump( $where);die;
        //查询数据
        $list = db('register')
            ->order('id DESC')
            ->where($where)
            ->paginate(20);
        //查询等级
        $rank = db('rank')->order('sort ASC')->paginate(20);
        $page = $list->render();
        $this->assign('page', $page);
        $this->assign('rank',$rank);
        $this->assign('list',$list);
    }
    //查看邀请人
    public function lookRegister(){
        $id = request()->param('id');
        if(empty($id)){
            $this->error('缺少参数');
            return;
        }
        $res = db('register')->where('id',$id)->find();
        if($res){
            $this->assign('vo',$res);
            return $this->fetch();
        }else{
            return '没有上级邀请';
        }
    }
    //查看下级
        public function xiaji(){
        $id = request()->param('id');
        if(empty($id)){
            $this->error('缺少参数');
            return;
        }
        $res = db('register')->where('pid',$id)->select()->toArray();
       //dump($res);
        if(empty($res)){
            echo '<h2 style="width:100%;text-align:center;">暂时没有下级哦<br/>请再接再厉</h2>';
            return;
        }
        $this->assign('list',$res);
        return $this->fetch();

    }

    //添加用户
    public function adduser(){
        $data = request()->param();
        if(!empty($data)){
            $data['create_time'] = time();
            if(empty($data['name'])){
                $this->error('填写姓名');
                return;
            }elseif (empty($data['phone'])){
                $this->error('请填写手机');
                return;
            }
            if(!empty($data['money'])){
                 $lev_money = $data['money'];
                 $data['lev'] = 2;

            }else{
                $data['lev'] = 1;
            }
            unset($data['money']);
            //查询手机号是否注册
            $is_mob = db('register')->where('phone',$data['phone'])->find();
            if($is_mob){
                $this->error('手机号已经注册');
                return;
            }
            if(!empty($data['pid'])){
                $res = db('register')->where('phone',$data['pid'])->find();
                if(empty($res)){
                    $this->error('邀请人没有注册');
                    return;
                }else{
                    $data['pid'] = $res['id'];
                }
            }
            $result = db('register')->insertGetId($data);
            if($result){
                //如果有入会费用
                if(isset($lev_money)){
                    $add_reg_rank = db('reg_rank')->insertGetId(['reg_id'=>$result,'rank_id'=>2,'create_time'=>time()]);
                    //写入消费表
                    $add_consume = db('consume_logs')->insert(['register_id'=>$result,'money'=>$lev_money,'create_time'=>time(),'status'=>0,'year'=>date('Y',time()),'moth'=>date('m',time())]);
                }else{
                    $add_reg_rank = db('reg_rank')->insertGetId(['reg_id'=>$result,'rank_id'=>1,'create_time'=>time()]);
                }
                if(!empty($data['pid'])){
                   //查询邀请人邀请的人数
                    $con = db('register')->where('pid',$res['id'])->where('lev',2)->count();
                    //等级
                    $lev = db('rank')->select()->toArray();
                    foreach($lev as $k =>$v){
                        if($con == $v['num']){
                            db('register')->where('id',$res['id'])->update(['lev'=>$v['id']]);
                        }
                    }
                    //10人主任  50人社长 100主席

                }
                $this->success('添加成功');
            }else{
                $this->error('网络错误');
            }
           //dump($data);
        }
        //查询等级
        $rank = db('rank')->order('sort ASC')->select();
        $list = db('company')->select();
        $this->assign('rank',$rank);
        $this->assign('list',$list);
        return $this->fetch();
    }

    //添加消费记录
    public function addConsume(){
        $money = request()->post('money');
        $id = request()->param('id');
        $type = request()->post('type',1);
        $goods_id = request()->post('goods_id');
        if(empty($id)){
            $this->error('缺少id');
            return;
        }
        if($money){
            $pid = db('register')->where('id', $id)->value('pid');
            $rank_id = db('register')->where('id',$pid)->value('lev');
            $data['register_id']=$id;
            $data['money'] = $money;
            $data['create_time'] = time();
            $data['status'] = $type;
            if(isset($goods_id) && !empty($goods_id)){
                $data['goods_id'] = $goods_id;
            }
            if(isset($rank_id) && !empty($rank_id)){
                $data['rank_id'] = $rank_id;
            }
            $data['year'] = date('Y',time());
            $data['moth'] = date('m',time());
            $res = db('consume_logs')->insertGetId($data);

            if($res){
                if($type == 0){
                    //更改会员等级
                    $lev = db('rank')->where('sort',1)->find();
                    db('register' )->where('id',$id)->update(['lev'=>$lev['id']]);
                }
                //查看是否有上级
                $is_parent = db('register')->where('id',$id)->value('pid');
                if($is_parent){
                    //如果有上级 查出上级的等级 和利率
                    $date = mktime(0,0,0,date('m'),1,date('Y'));
                  //  dump($date);die;
                    $where['create_time'] = ['lt',$date];
                    $where['reg_id'] = $is_parent;
                    //dump($date);die;
                    $reg_rank = db('reg_rank')->where($where)->order('create_time DESC')->find();
                    //dump($reg_rank);die;
                    $info = db('rank')->where('id',$reg_rank['rank_id'])->find();
                  //  $info = db('register')->alias('rr')->join('rank rk','rk.id = rr.lev')->field('rr.id as reg_id,rk.*')->where('rr.id',$is_parent)->find();
                 // dump($info);die;
                    //写入收益表
                    if($info['bonus']){
                        $map = ['inco_reg_id'=>$is_parent,'create_time'=>time(),'inco_money'=>$data['money']*$info['bonus'],'consu_id'=>$res];
                        db('income')->insert($map);
                        // dump($info);die;
                    }

                }
                $this->success('消费成功');
                return;
            }else{
                $this->error('消费失败');
                return;
            }
        }
        $register = db('register')->where('id',$id)->find();
        $goodsList = db('goods')->where(array('is_del'=>0))->select();
        $this->assign('goodsList', $goodsList);
        $this->assign('register', $register);
        $this->assign('id',$id);
        return $this->fetch();

    }
    //删除用户
    public function delUser(){
        $id = request()->param('id');
        if(empty($id)){
            $this->error('缺少参数');
            return;
        }
        $res = db('register')->where('id',$id)->update(['is_del'=>1]);
        if($res){
            $this->success('删除成功');
        }else{
            $this->error('删除失败');
        }
    }

    //查看
    public function userInfo(){
        //查询基本信息
        $id = request()->param('id');
        $info = db('register')->where('id',$id)->find();
        //查询会员等级
        $lev = db('reg_rank')
            ->alias('rr')
            ->order('rr.rank_id asc')
            ->join('rank rk','rk.id = rr.rank_id')
            ->where('rr.reg_id',$id)->select();
        //会员当前等级
        $now_lev = db('rank')->where('id',$info['lev'])->find();
        //入会金额
        $money = db('consume_logs')->where(['register_id'=>$id,'status'=>0])->find();
        //个人消费
        $cons = db('consume_logs')->where(['register_id'=>$id,'status'=>['neq',0] ])->sum('money');
        //总收益
        $info['all_money'] = getRegisterTotalConsume($id);
        //用户升级记录
        $all_reg_rank = db('reg_rank')->where('reg_id',$id)->select();
        $year = date('Y');
        //用户总积分
        $totalIntegral = db('integral')->where('user_id', $id)->sum('integral');


        $this->assign('totalIntegral', $totalIntegral);
        $this->assign('cons',$cons);
        $this->assign('info',$info);
        $this->assign('lev',$lev);
        $this->assign('now_lev',$now_lev);
        $this->assign('money',$money);
        $this->assign('year', $year);
        $this->assign('all_reg_rank', $all_reg_rank);
        return $this->fetch();
    }

    //修改
    public function editInfo(){
        $data = request()->param();

        if($data){
            if(empty($data['id'])){
                $this->error('缺少id');
            }elseif (empty($data['name'])){
                $this->error('请填写姓名');
            }elseif (empty($data['age'])){
                $this->error('请填写年龄');
            }elseif (empty($data['phone'])){
                $this->error('请填写手机');
            }
        }

        if(!empty($data['money'])){
            //更改等级 更改消费记录 更改等级记录
            $add_reg_rank = db('reg_rank')->insertGetId(['reg_id'=>$data['id'],'rank_id'=>2,'create_time'=>time()]);
            //写入消费表
            $add_consume = db('consume_logs')->insert(['register_id'=>$data['id'],'money'=>$data['money'],'create_time'=>time(),'status'=>0,'year'=>date('Y',time()),'moth'=>date('m',time())]);
             db('register')->where('id',$data['id'])->update(['lev'=>2]);

        }

        $id = $data['id'];
        unset($data['id']);
        unset($data['money']);
        $data['update_time'] = time();
        $edit_reg = db('register')->where('id',$id)->update($data);

        if($edit_reg){
            $this->success('修改成功');
        }else{
            $this->error('修改失败');
        }

    }

    //个人消费
    public function consumes(){

        $id =request()->param('id');
        $year = $this->request->param('year', null);
        $moth = $this->request->param('moth', 0, 'int');

        if(empty($year))
            $year = date('Y');
        if (empty($moth))
            $moth = date('m');
        if(empty($id)){
            $this->error('缺少参数');
            return;
        }

        $userInfo = db('register')->where('id', $id)->find();

        //获取前五年的数组
        //$years = getFiveYears();
        //获取12月的月份
       // $moths = getMoths();
        //每月总消费
        $all_con = db('consume_logs')->where(['register_id'=>$id,'status'=>['neq',0], 'year'=>$year])->field("*,sum(money) shouyi, FROM_UNIXTIME(create_time,'%c') time")->group("time")->select()->toArray();
        //通过每月消费的总额，给月份数组moths赋值
        /*foreach ($all_con as $value) {
            if ($value['time'] == $moths[$value['moth']]['moth']){
                $moths[$value['moth']]['total_money'] = $value['shouyi'];
            }
        }*/

        //查询每月的消费记录
        $field = "c.id, c.moth, c.register_id, c.year, c.money, c.create_time, r.sex, r.name, r.phone, g.goods_name";
        $join = [
            ['hstht_register r', 'r.id=c.register_id', 'LEFT'],
            ['hstht_goods g', 'g.id=c.goods_id', 'LEFT'],
        ];
        $where = array(
            'c.register_id' => $id,
            'c.status'    => 1,
            'c.year'    => $year,
            //'c.moth'    => $moth
        );

        $list = db('consume_logs')->alias('c')->field($field)->join($join)->where($where)->paginate(1000);

        foreach ($all_con as $key=>$val) {
            foreach ($list as $k=>$v){
                if ($val['time'] == $v['moth']){
                    $all_con[$key]['sub'][] = $v;
                }
            }
        }

       // $this->assign('moths', $moths);
        //$this->assign('years', $years);
        $this->assign('list', $all_con);
        $this->assign('year',$year);
        $this->assign('moth',$moth);
        $this->assign('userInfo',$userInfo);
       // $this->assign('page', $page);
        return $this->fetch();
    }

    public function delete(){
        $id = $this->request->param('id');

        $result = db('consume_logs')->delete($id);
        if (!$result){
            $this->error('删除失败');
        }
        $income = db('income')->where('consu_id', $id)->find();
        if($income){
            db('income')->where('consu_id', $id)->delete();
        }
        $this->success('删除成功');
    }


    public function addIntegral(){
        $userId = $this->request->param('id');

        return $this->fetch('', array(
            'userId' => $userId
        ));
    }

    public function addIntegralPost(){
        $data = $this->request->param();
        $data['create_time'] = time();
        $rest = \db('integral')->insert($data);
        if (!$rest){
            $this->error('添加失败');
        }
        $this->success('添加成功');
    }

    public function lookIntegral(){
        $userId = $this->request->param('id');

        $list = db('integral')->where('user_id', $userId)->order('create_time desc')->select()->toArray();
        //dump($list);die;
        return $this->fetch('', array(
            'list' => $list
        ));
    }

    public function deleteIntegral(){
        $id = $this->request->param('id');
        $num = db('integral')->delete($id);
        if (!$num){
            $this->error('删除失败');
        }
        $this->success('删除成功');
    }

}